import React, { Fragment } from 'react';
import ReactDOM from 'react-dom';
import MyIcon from '@/components/MyIcon';

import styles from './index.less';

interface IToastParams {
  /** Toast消失时间 */
  time?: number;
  /** Toast类型 */
  type?: 'success';
  /** Toast文本内容 */
  content?: React.ReactNode;
}

const ToastConfig = {
  success: '#1AB857',
};

const showToast = (params: IToastParams) => {
  const { time = 1.5, type = 'success', content } = params;

  const element = document.createElement('div');

  const toast = (
    <Fragment>
      <div className={styles.toast}>
        <div>
          <MyIcon
            type="iconchenggong"
            className={styles.toastIcon}
            style={{ color: ToastConfig[type] }}
          />
        </div>
        {content ? <div className={styles.toastContent}>{content}</div> : null}
      </div>
      <div className={styles.toastMask}></div>
    </Fragment>
  );

  function destroy() {
    const unmountResult = ReactDOM.unmountComponentAtNode(element);
    if (unmountResult && element.parentNode) {
      element.parentNode.removeChild(element);
    }
  }

  setTimeout(() => {
    document.body.appendChild(element);
    ReactDOM.render(toast, element);
  }, 500);

  setTimeout(() => {
    destroy();
  }, time * 1000);
};

export default showToast;
